package cn.straosp.workrecord.dao

import org.ktorm.database.Database
import org.ktorm.entity.Entity
import org.ktorm.entity.add
import org.ktorm.entity.all
import org.ktorm.entity.count
import org.ktorm.entity.filter
import org.ktorm.entity.find
import org.ktorm.entity.removeIf
import org.ktorm.entity.sequenceOf
import org.ktorm.entity.toList
import org.ktorm.entity.update
import org.ktorm.schema.ColumnDeclaring
import org.ktorm.schema.Table
import org.springframework.beans.factory.annotation.Autowired

abstract class BaseDao<E: Entity<E>, T: Table<E>>(private val table: T) {

    @Autowired
    protected lateinit var database: Database

    open fun add(entity: E): Int {
        return database.sequenceOf(table).add(entity)
    }
    open fun update(entity: E): Int {
        return database.sequenceOf(table).update(entity)
    }
    open fun deleteIf(predicate: (T) -> ColumnDeclaring<Boolean>): Int {
        return database.sequenceOf(table).removeIf(predicate)
    }
    open fun allMatched(predicate: (T) -> ColumnDeclaring<Boolean>): Boolean {
        return database.sequenceOf(table).all(predicate)
    }
    open fun count(): Int {
        return database.sequenceOf(table).count()
    }
    open fun findOne(predicate: (T) -> ColumnDeclaring<Boolean>): E? {
        return database.sequenceOf(table).find(predicate)
    }
    open fun findList(predicate: (T) -> ColumnDeclaring<Boolean>): List<E> {
        return database.sequenceOf(table).filter(predicate).toList()
    }
    open fun findAll(): List<E> {
        return database.sequenceOf(table).toList()
    }

}